package com.rupertjones.globalcron.config;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class Log4jConfigurator {

    private static final Logger LOG = Logger.getLogger(Log4jConfigurator.class);
    private String home = null;

    public Log4jConfigurator() {
        home = System.getenv("GLOBAL_CRON_HOME");
        init();
    }

    private void init() {
        String file = home + "/log4j.xml";
        LOG.info("Attempting to find logging configuration at " + file);
        InputStream stream = null;
        try {
            stream = new FileInputStream(new File(file));
        } catch (FileNotFoundException e) {
            LOG.warn(e);
        }

        if (stream == null) {
            stream = this.getClass().getResourceAsStream("/log4j.xml");
            LOG.warn("Couldn't find outside log4j configuration, using internal");
        }
        DOMConfigurator configurator = new DOMConfigurator();
        configurator.doConfigure(stream, LogManager.getLoggerRepository());
        LOG.info("Logging configured.");
    }
}
